import {readDir, nodeFileSys, getStatOf} from "./NodeEnhance/fileSys";
import {LOCAL_ROOT_DIR} from "./app-vars";
import {joinPath} from "./NodeEnhance/path";
export interface IPictureDirItem {
    name: string;
    list: string[];
}
async function getPictureDirListIn(dirList: string[]) {
    const imgDirTestList: Promise<nodeFileSys.Stats>[] = [];
    dirList.forEach((dir) => {
        imgDirTestList.push(getStatOf(joinPath(LOCAL_ROOT_DIR, dir)));
    });
    const imgDirTestResultList = await Promise.all(imgDirTestList);
    const pictureDirList: string[] = [];
    imgDirTestResultList.forEach((result, index) => {
        if (result.isDirectory()) {
            pictureDirList.push(dirList[index]);
        }
    });
    return pictureDirList;
}

async function getPictureListInDir(dirname: string) {
    const list: string[] = await readDir(dirname);
    return list.filter((item) => {
        return /\.(png|jpg|jpeg)$/.test(item);
    });
}

export async function getPictureList(): Promise<IPictureDirItem[]> {
    const dirList = await readDir(LOCAL_ROOT_DIR);
    const pictureDirList = await getPictureDirListIn(dirList);
    const pictureItemPromiseList: Promise<string[]>[] = pictureDirList.map((dirname) => {
        return getPictureListInDir(joinPath(LOCAL_ROOT_DIR, dirname));
    });
    const resultList = await Promise.all(pictureItemPromiseList);
    return resultList.map((itemList, index) => {
        return {
            name: dirList[index],
            list: itemList,
        };
    });
}
